<template>
  <div class="container">
    <!-- 页面名称 -->
    <div class="header">
      <span>组织机构</span>
    </div>

    <!-- 内容 -->
    <el-container class="body">
      <!-- 树形 -->
      <!-- <el-aside width="200px" class="mainaside">
        <div class="user_tree">
          <el-tree
            class="el-tree"
            ref="treeRef"
            :props="treeprops"
            :data="treeDate"
            node-key="fId"
            check-strictly="true"
            @current-change="selectTable"
          />
        </div>
      </el-aside> -->
      <el-main class="mainmain">
        <div class="firsthe">
          <!-- 新增按钮及查询 -->
          <el-button
            type="primary"
            class="add"
            @click="onHandleAdd"
            :v-if="pageData.permissions.Add"
            style="padding-left: 30px; padding-right: 30px"
          >
            <el-icon style="margin-right: 6px"><CirclePlus /></el-icon>
            新增
          </el-button>
          <el-dialog
            :width="500"
            :title="pageData.orgEditDialogTitle"
            v-model="pageData.orgEditDialogVisible"
            destroy-on-close
            custom-class="editDialog-class"
          >
            <orgedit
              :orgObj="pageData.tableParams.currentRow"
              :isAdd="pageData.orgIsAdd"
              @Ok="onOk"
              @Cancel="() => (pageData.orgEditDialogVisible = false)"
            />
          </el-dialog>

          <!-- <el-dialog
            :width="500"
            :title="pageData.orgEditDialogTitle"
            v-model="pageData.orgEditDialogVisible"
            :close-on-click-modal="false"
            destroy-on-close
            custom-class="editDialog-class"
          >
            <edit
              :orgObj="pageData.tableParams.currentRow"
              :isAdd="pageData.orgIsAdd"
              @Ok="onOk"
              @Cancel="() => (pageData.orgEditDialogVisible = false)"
            />
          </el-dialog> -->

          <!-- <div class="search">
            <el-input
              v-model="pageData.queryParams.fcode"
              placeholder="请输入组织编号"
              clearable
              ><template #prepend>组织编号</template>
            </el-input>

            <el-button type="primary" plain @click="onHandleSearch"
              >搜索</el-button
            >
            <el-button type="warning" plain @click="onHandleReset"
              >重置</el-button
            >
          </div> -->
        </div>

        <el-row class="row-2">
          <el-table
            ref="orgTable"
            class="org-table"
            row-key="forgid"
            lazy
            stripe
            border
            highlight-current-row
            v-loading="pageData.tableParams.tableLoading"
            :load="tableLoad"
            :tree-props="pageData.tableParams.props"
            :data="pageData.tableParams.tableData"
            @current-change="(row) => (pageData.tableParams.currentRow = row)"
          >
            <el-table-column prop="fname" label="名称" min-width="180">
            </el-table-column>
            <el-table-column prop="fcode" label="编号" min-width="180">
            </el-table-column>
            <el-table-column
              prop="funittypeid"
              label="类型"
              width="80"
              align="center"
              :formatter="orgTypeFormatter"
            >
            </el-table-column>
            <el-table-column
              prop="fmanager"
              label="负责人"
              width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="ftel"
              label="电话"
              width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="fremark"
              label="备注"
              width="100"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="forder"
              label="排序"
              width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="140"
              align="center"
              show-overflow-tooltip
              :v-if="pageData.permissions.Edit || pageData.permissions.Del"
            >
              <template #default="{ row }">
                <el-button
                  id="edit"
                  link
                  type="primary"
                  size="small"
                  @click="onHandleEdit(row)"
                  :v-if="pageData.permissions.Edit"
                  >编辑</el-button
                >

                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="onHandleDel(row.forgid)"
                  :v-if="pageData.permissions.Del && !isEmpty(row.faboveid)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页查询 -->
          <!-- <el-col :span="24">
            <el-pagination
              style="margin-top: 20px"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="pageData.tableParams.pageSizeOptions"
              :current-page="pageData.queryParams.page"
              :page-size="pageData.queryParams.pageSize"
              :total="pageData.tableParams.totalCount"
              @current-change="onHandleCurrentChange"
              @size-change="onHandleSizeChange"
            >
            </el-pagination>
          </el-col> -->
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { onMounted, nextTick, reactive, ref, toRefs } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import utils from "@/common/utils";
import enums from "@/common/enums";

import { getOrgList, deleteOrg } from "@/api/system";
import orgedit from "./edit";
import { CirclePlus } from "@element-plus/icons-vue";

export default {
  name: "OrgInfo",
  components: { orgedit, CirclePlus },
  setup(props, context) {
    onMounted(() => {
      getOrgList("")
        .then((ret) => {
          console.log("返回的是树父节点ret", ret);
          pageState.pageData.tableParams.tableData = ret;
          if (ret.length > 0) {
            nextTick(() => {
              const nodeObj =
                orgTable.value?.store.states.treeData.value[ret[0].forgid];
              if (nodeObj) {
                nodeObj.loaded = false;
                orgTable.value?.store.loadOrToggle(ret[0]);
              }
            });
          }
        })
        .catch((error) => {
          ElMessage.error(error.message || "请求出错");
        });
    });

    const orgTable = ref();
    const pageState = reactive({
      pageData: {
        permissions: {
          Add: utils.checkPermission("orginfo_add"),
          Del: utils.checkPermission("orginfo_delete"),
          Edit: utils.checkPermission("orginfo_edit"),
        },
        orgTypeEnumObj: enums.OrgTypeEnum,
        tableParams: {
          tableLoading: false,
          tableHeight: 0,
          // tableColumns: [],
          props: { children: "children", hasChildren: "haschildren" },
          tableData: [],
          currentRow: {},
        },

        orgEditDialogTitle: "机构",
        orgEditDialogVisible: false,
        orgIsAdd: false,
      },
    });
    const pageFunc = {
      isEmpty: utils.isEmpty,
      tableLoad: (row, treeNode, resolve) => {
        getOrgList(row.forgid)
          .then((ret) => {
            console.log("返回是点击父节点传回的子节点数据", ret);
            resolve(ret);
          })
          .catch((error) => {
            ElMessage.error(error.message || "请求出错");
          });
      },
      orgTypeFormatter: (row, column, cellValue, index) => {
        return pageState.pageData.orgTypeEnumObj.getLabelByValue(cellValue);
      },

      // 新增组织机构
      onHandleAdd: () => {
        if (utils.isEmpty(pageState.pageData.tableParams.currentRow)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        pageState.pageData.orgEditDialogTitle = "新增";
        pageState.pageData.orgEditDialogVisible = true;
        pageState.pageData.orgIsAdd = true;
      },
      // 编辑修改
      onHandleEdit: (row) => {
        if (utils.isEmpty(row)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        if (utils.isEmpty(row.faboveid)) {
          ElMessage.warning("顶级机构不允许编辑");
          return;
        }
        pageState.pageData.tableParams.currentRow = row;
        pageState.pageData.orgEditDialogTitle = "编辑";
        pageState.pageData.orgEditDialogVisible = true;
        pageState.pageData.orgIsAdd = false;
      },
      // 删除
      onHandleDel: (id) => {
        if (utils.isEmpty(id)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        ElMessageBox.confirm("此操作将删除该机构, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const loading = ElLoading.service({
              lock: true,
              background: "rgba(0, 0, 0, 0.7)",
            });
            deleteOrg(id)
              .then((res) => {
                // console.log("删除", res);
                // if (res.code === 200) {
                //   loading.close();
                //   ElMessage.success("删除成功");
                //   reloadParentNode(id);
                //   pageFunc.tableLoad(id)
                // }
                loading.close();
                ElMessage.success("删除成功");
                reloadParentNode(id);
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          })
          .catch(() => {});
      },
      onOk: ({ isAdd, keyId }) => {
        pageState.pageData.orgIsAdd = isAdd;
        pageState.pageData.orgEditDialogVisible = false;
        if (isAdd) reloadNode(keyId);
        else reloadParentNode(keyId);
      },
    };
    const reloadNode = (keyId) => {
      if (utils.isEmpty(keyId)) return;
      const nodeObj = orgTable?.value?.store.states.treeData.value[keyId];
      if (nodeObj) {
        nodeObj.loaded = false;
        orgTable?.value?.store.loadOrToggle({
          forgid: keyId,
          haschildren: true,
        });
      } else reloadParentNode(keyId);
    };
    const reloadParentNode = (keyId) => {
      if (utils.isEmpty(keyId)) return;
      let tmpKeyId = "";
      let nodeObj = {};
      for (const ikey in orgTable?.value?.store.states.treeData.value) {
        const sub_idx = orgTable?.value?.store.states.treeData.value[
          ikey
        ].children.findIndex((q) => q === keyId);
        if (sub_idx > -1) {
          tmpKeyId = ikey;
          nodeObj = orgTable?.value?.store.states.treeData.value[ikey];
          break;
        }
      }
      if (!utils.isEmpty(nodeObj)) {
        nodeObj.loaded = false;
        orgTable?.value?.store.loadOrToggle({
          forgid: tmpKeyId,
          haschildren: true,
        });
      }
    };

    // 主要组织机构不能编辑和删除
    // const aaa = (row) => {
    //   console.log("object", row);
    //   // var edit = ref(document.getElementById("edit"));

    //   // if(edit)
    //   // edit.style.color = "red";
    // };

    return {
      orgTable,
      ...toRefs(pageState),
      ...pageFunc,
      // aaa,
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 0;
  margin: 0;
  .header {
    width: 100%;
    background-color: white;
    user-select: none;

    text-align: left;
    span {
      line-height: 50px;
      font-size: 18px;
      font-weight: 700;
      text-align: left;
      margin-left: 20px;
    }
  }

  .body {
    margin-top: 20px;
    background-color: white;
    height: 77vh;
    // 树形下拉框
    .mainaside {
      background-color: rgb(230, 240, 250);
      border-right: 1px solid #ccc;
      .user_tree {
        .el-tree {
          border-bottom: 1px solid #ddd;
        }
      }
    }
    // 内容表格
    .mainmain {
      .firsthe {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .search {
          display: flex;
          align-items: center;
          user-select: none;

          .el-input {
            margin-right: 20px;
          }
        }
      }
    }
  }
}
</style>

<style>
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  user-select: none;
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
.el-dialog .el-dialog__header {
  padding: 20px 0;
  padding-left: 20px;
  margin: 0;

  word-break: break-all;
  border-bottom: 1px solid #ddd;
  text-align: left;
}

.el-select {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-select .el-option {
  width: 100%;
  border: none;
  border-radius: 0;
}
</style>
